package ldkxingzhe.ldkxingzhedemo.drawable;

import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.util.Log;

/**
 * Created by ke on 16-4-17.
 */
public class ProgressBarDrawable extends Drawable{
    @SuppressWarnings("unused")
    private static final String TAG = "ProgressBarDrawable";

    private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    private int mBackgroundColor = 0x80000000;
    private int mColor = 0x800080FF;
    private int mPadding = 10;
    private int mBarWidth = 20;
    private int mLevel = 0;
    private boolean mHideWhenZero = false;

    public void setColor(int color){
        if(mColor != color){
            mColor = color;
            invalidateSelf();
        }
    }

    public int getColor(){
        return mColor;
    }

    public void setPadding(int padding){
        if(mPadding != padding){
            mPadding = padding;
            invalidateSelf();
        }
    }

    public int getpadding(){
        return mPadding;
    }

    public void setBarWidth(int barWidth){
        if(mBarWidth != barWidth){
            mBarWidth = barWidth;
            invalidateSelf();
        }
    }

    public int getBarWidth(){
        return mBarWidth;
    }

    @Override
    protected boolean onLevelChange(int level) {
        Log.v(TAG,"onLevelChnaged, and level is " + level);
        mLevel = level;
        invalidateSelf();
        return true;
    }

    @Override
    public void draw(Canvas canvas) {
        Log.v(TAG,"draw");
        if(mHideWhenZero && mLevel == 0){
            return;
        }

        drawBar(canvas, 1000, mBackgroundColor);
        drawBar(canvas, mLevel, mColor);
    }

    private void drawBar(Canvas canvas, int level, int color) {
        Rect bounds = getBounds();
        int length = (bounds.width() - 2 * mPadding) * level / 1000;
        int xpos = bounds.left + mPadding;
        int ypos = bounds.bottom - mPadding - mBarWidth;
        mPaint.setColor(color);
        canvas.drawRect(xpos, ypos, xpos + length, ypos + mBarWidth, mPaint);
    }

    @Override
    public void setAlpha(int alpha) {
        mPaint.setAlpha(alpha);
    }

    @Override
    public void setColorFilter(ColorFilter colorFilter) {
        mPaint.setColorFilter(colorFilter);
    }

    @Override
    public int getOpacity() {
        return 0;
    }
}
